<template>
  <div class="inspection-item">
    <!-- 第一行：是否单选框 + input文本输入框 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- mode=0: 显示是/否单选 -->
        <el-form-item v-if="mode === 0" :label="titles[0]" :prop="fieldNames[0]">
          <el-radio-group 
            :value="localValue[fieldNames[0]]" 
            @input="updateValue(fieldNames[0], $event)"
          >
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- mode=1: 显示可点击的字段名 -->
        <el-form-item 
          v-else 
          :prop="fieldNames[0]"
          class="mode-1-field"
          label-width="0px"
        >
            <el-checkbox 
              :value="localValue[fieldNames[0]] === 1"
              @change="handleCheckboxChange"
            >
              {{ titles[0] }}
            </el-checkbox>
        
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="titles[1] && shouldShowOtherFields">
        <el-form-item :label="titles[1]" :prop="fieldNames[1]">
          <el-input 
            :value="localValue[fieldNames[1]]"
            @input="updateValue(fieldNames[1], $event)"
            placeholder="请输入相关信息"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二行：附件上传 -->
    <el-row v-if="shouldShowOtherFields">
      <el-col :span="24">
        <el-form-item :label="titles[2]" :prop="fieldNames[2]">
    
          <ImageUpload
            v-model="localValue[fieldNames[2]]"
            :show-tips="true"
            @input="updateValue(fieldNames[2], $event)"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第三行：textarea -->
    <el-row v-if="shouldShowOtherFields">
      <el-col :span="24">
        <el-form-item :label="titles[3]" :prop="fieldNames[3]">
          <el-input
            :value="localValue[fieldNames[3]]"
            @input="updateValue(fieldNames[3], $event)"
            type="textarea"
            :rows="3"
            :placeholder="titles[3].includes('描述') ? '请输入详细描述' : '请输入相关信息'"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload.vue'

export default {
  name: 'InspectionItem',
  components: {
    ImageUpload
  },
  props: {
    // 4个字段的标题数组：[是否问题标题, input标题, 附件标题, textarea标题]
    titles: {
      type: Array,
      required: true,
      validator: (value) => Array.isArray(value) && value.length === 4
    },
    // 4个字段在formData中的字段名称数组：[是否字段名, input字段名, 附件字段名, textarea字段名]
    fieldNames: {
      type: Array,
      required: true,
      validator: (value) => Array.isArray(value) && value.length === 4
    },
    // v-model 绑定的完整formData对象
    value: {
      type: Object,
      default: () => ({})
    },
    // 显示模式：0-默认模式(是/否单选)，1-字段名点击模式
    mode: {
      type: Number,
      default: 0,
      validator: (value) => [0, 1].includes(value)
    }
  },
  data() {
    return {
      localValue: {}
    }
  },
  computed: {
    // 判断是否显示其他字段（当第一个字段选择"是"时显示）
    shouldShowOtherFields() {
      return this.localValue[this.fieldNames[0]] === 1
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          this.localValue = { ...newVal }
        }
      },
      immediate: true,
      deep: true
    },
    // 监听第一个字段的变化，当选择"否"时清空其他字段
    shouldShowOtherFields(newVal) {
      if (!newVal) {
        // 当选择"否"(0)时，清空其他三个字段的值
        this.updateValue(this.fieldNames[1], '')
        this.updateValue(this.fieldNames[2], '')
        this.updateValue(this.fieldNames[3], '')
      }
      // 更新验证规则
      this.updateValidationRules()
    },
    // 监听localValue深层变化，更新验证规则
    localValue: {
      handler(newVal, oldVal) {
        if (oldVal && this.fieldNames[0] && newVal[this.fieldNames[0]] !== oldVal[this.fieldNames[0]]) {
          this.updateValidationRules()
        }
      },
      deep: true
    }
  },
  mounted() {
    // 组件挂载后初始化验证规则
    this.$nextTick(() => {
      this.updateValidationRules()
    })
  },
  beforeDestroy() {
    // 组件销毁前清理验证规则
    this.cleanupValidationRules()
  },
  methods: {
    updateValue(fieldName, newValue) {
      this.localValue[fieldName] = newValue
      // 触发v-model更新
      this.$emit('input', { ...this.localValue })
    },
    
    // mode=1时点击字段名的处理函数
    handleMode1Click(event) {
      if (this.mode === 1) {
        // 如果点击的是checkbox本身，不处理（避免重复触发）
        if (event.target.tagName === 'INPUT' || event.target.closest('.el-checkbox')) {
          return
        }
        // 点击后切换选中状态
        const currentValue = this.localValue[this.fieldNames[0]]
        const newValue = currentValue === 1 ? 0 : 1
        this.updateValue(this.fieldNames[0], newValue)
      }
    },
    
    // mode=1时checkbox变化的处理函数
    handleCheckboxChange(checked) {
      const newValue = checked ? 1 : 0
      this.updateValue(this.fieldNames[0], newValue)
    },
    
    // 更新验证规则
    updateValidationRules() {
      // 获取父组件的rules对象
      let parent = this.$parent
        while (parent && !parent.rules) {
          parent = parent.$parent
        }
      const  parentRules = parent && parent.rules
      if (!parentRules) return
      
      // 第一个字段（是否存在问题）始终必填
      this.$set(parentRules, this.fieldNames[0], [
        { required: true, message: '请选择是否存在问题', trigger: 'submit' }
      ])
      
      // 根据第一个字段的值动态设置其他字段的验证规则
      if (this.localValue[this.fieldNames[0]] === 1) {
        // 如果选择"是"，其他字段必填
        this.$set(parentRules, this.fieldNames[1], [
          { required: true, message: '此项为必填项', trigger: 'submit' }
        ])
        this.$set(parentRules, this.fieldNames[2], [
          { required: true, message: '此项为必填项', trigger: 'submit' }
        ])
        this.$set(parentRules, this.fieldNames[3], [
          { required: true, message: '此项为必填项', trigger: 'submit' }
        ])
      } else {
        // 如果选择"否"或未选择，移除其他字段的验证规则
        this.$delete(parentRules, this.fieldNames[1])
        this.$delete(parentRules, this.fieldNames[2])
        this.$delete(parentRules, this.fieldNames[3])
      }
    },
    
    // 清理验证规则
    cleanupValidationRules() {
      // 获取父组件的rules对象
      let parent = this.$parent
        while (parent && !parent.rules) {
          parent = parent.$parent
        }
      const  parentRules = parent && parent.rules
      if (!parentRules) return
      
      // 移除所有相关的验证规则
      this.fieldNames.forEach(fieldName => {
        this.$delete(parentRules, fieldName)
      })
    }
  }
}
</script>

<style scoped>
.inspection-item {
  margin-bottom: 10px;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

/* mode=1样式 */
.mode-1-field {
  margin-bottom: 0;
  border-radius: 4px;
  transition: all 0.2s ease;
  border-bottom: 3px solid transparent;
}

.mode-1-field {
  border-bottom: 3px solid #409eff;
}

/* 隐藏mode=1时的label */
.mode-1-field ::v-deep .el-form-item__label {
  display: none;
}

.mode-1-container {
  cursor: pointer;
  padding: 0 10px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.mode-1-container:hover {
  background-color: #f5f7fa;
}

.mode-1-field.mode-1-container {
  background-color: #ecf5ff;
}

/* mode=1时的checkbox样式 */
.mode-1-container ::v-deep .el-checkbox {
  width: 100%;
}

.mode-1-container ::v-deep .el-checkbox__label {
  font-size: 14px;
  color: #606266;
  padding-left: 8px;
}


/* 移动端响应式 */
@media (max-width: 768px) {
  .inspection-item {
    padding: 15px;
  }
  
  ::v-deep .el-form-item__label {
    line-height: 1.2 !important;
  }
}
</style>